﻿#include <iostream>
#include <string>
#include <winsock2.h>  // 包含WinSock2库
#pragma comment(lib, "ws2_32.lib")  // 链接Winsock库

#pragma warning(disable: 4996)

using namespace std;

int main() {

    SetConsoleOutputCP(CP_UTF8);
    // 初始化WinSock库
    WSADATA wsaData;
    int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (result != 0) {
        std::cerr << "WinSock初始化失败！错误代码：" << result << std::endl;
        return 1;
    }

    // 创建套接字
    SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket == INVALID_SOCKET) {
        std::cerr << "创建套接字失败！错误代码：" << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    // 设置服务器地址
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(8888);  // 服务器端口
    serverAddr.sin_addr.s_addr = inet_addr("119.3.219.187");  // 服务器IP地址

    // 连接到服务器
    result = connect(clientSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));
    if (result == SOCKET_ERROR) {
        std::cerr << "连接失败！错误代码：" << WSAGetLastError() << std::endl;
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    //std::cout << "已连接到服务器" << std::endl;

    // 发送数据到服务器


    //std::cout << "消息已发送: " << message << std::endl;

    // 接收服务器响应
    while (true)
    {
        std::string message;
        getline(cin ,message);
        result = send(clientSocket, message.c_str(), message.size(), 0);
        if (result == SOCKET_ERROR) {
            std::cerr << "发送数据失败！错误代码：" << WSAGetLastError() << std::endl;
            closesocket(clientSocket);
            WSACleanup();
            return 1;
        }

        char buffer[512];
        result = recv(clientSocket, buffer, sizeof(buffer), 0);
        if (result > 0) {
            buffer[result] = '\0';  // 确保字符串结束符
            std::cout << buffer << std::endl;
        }
        else if (result == 0) {
            std::cout << "服务器已关闭连接" << std::endl;
        }
        else {
            std::cerr << "接收数据失败！错误代码：" << WSAGetLastError() << std::endl;
        }
    }


    // 关闭套接字
    closesocket(clientSocket);
    WSACleanup();  // 清理WinSock资源

    return 0;
}
